// ==============================
// 🔥 GLOBAL DATA
// ==============================
let finalData = {};

// load existing data
chrome.storage.local.get(null, (data) => {
  finalData = data || {};
  if (!finalData.journey_details) {
    finalData.journey_details = {};
  }
});

// ==============================
// 📅 CALENDAR SYSTEM
// ==============================
document.addEventListener('DOMContentLoaded', () => {

  const dateInput = document.getElementById('journey-date');
  const calendarIcon = document.getElementById('calendar-icon');
  const calendarContainer = document.getElementById('calendar-container');
  const monthYearElement = document.getElementById('month-year');
  const prevMonthButton = document.getElementById('prev-month');
  const nextMonthButton = document.getElementById('next-month');
  const daysElement = document.getElementById('calendar-days');

  let currentDate = new Date();

  calendarIcon.onclick = (e) => {
    e.stopPropagation();
    calendarContainer.style.display =
      calendarContainer.style.display === "block" ? "none" : "block";
    renderCalendar();
  };

  dateInput.onclick = (e) => {
    e.stopPropagation();
    calendarContainer.style.display =
      calendarContainer.style.display === "block" ? "none" : "block";
    renderCalendar();
  };

  document.addEventListener('click', (e) => {
    if (!calendarContainer.contains(e.target)) {
      calendarContainer.style.display = 'none';
    }
  });

  calendarContainer.onclick = (e) => e.stopPropagation();

  function renderCalendar() {
    daysElement.innerHTML = "";

    let year = currentDate.getFullYear();
    let month = currentDate.getMonth();
    let today = new Date();

    let firstDay = new Date(year, month, 1).getDay();
    let lastDate = new Date(year, month + 1, 0).getDate();

    monthYearElement.innerText =
      currentDate.toLocaleString("default", { month: "long" }) + " " + year;

    for (let i = 0; i < firstDay; i++) {
      daysElement.appendChild(document.createElement("div"));
    }

    for (let i = 1; i <= lastDate; i++) {
      let day = document.createElement("div");
      day.innerText = i;

      if (
        i === today.getDate() &&
        month === today.getMonth() &&
        year === today.getFullYear()
      ) {
        day.style.background = "#22c55e";
        day.style.color = "white";
      }

      day.onclick = () => {
        let d = String(i).padStart(2, "0");
        let m = String(month + 1).padStart(2, "0");
        let formatted = `${d}/${m}/${year}`;

        dateInput.value = formatted;
        finalData.journey_details.date = formatted;
        chrome.storage.local.set(finalData);
        calendarContainer.style.display = "none";
      };

      daysElement.appendChild(day);
    }
  }

  nextMonthButton.onclick = () => {
    currentDate.setMonth(currentDate.getMonth() + 1);
    renderCalendar();
  };

  prevMonthButton.onclick = () => {
    currentDate.setMonth(currentDate.getMonth() - 1);
    renderCalendar();
  };


function validateForm() {

  // 🔐 LOGIN
  let username = document.getElementById("irctc-login").value.trim();
  let password = document.getElementById("irctc-password").value.trim();

  if (!username) {
    alert("❌ Username required");
    return false;
  }

  if (!password) {
    alert("❌ Password required");
    return false;
  }



  // 🚆 JOURNEY
  let from = document.getElementById("from").value.trim();
  let to = document.getElementById("to").value.trim();
  let date = document.getElementById("journey-date").value.trim();

  if (!from) {
    alert("❌ Source required");
    return false;
  }

  if (!to) {
    alert("❌ Destination required");
    return false;
  }

  if (!date) {
    alert("❌ Date required");
    return false;
  }

  // 🚆 CLASS & QUOTA
  let cls = document.getElementById("journey-class-input").value;
let quota = document.getElementById("quota-input").value;

if (!cls) {
  alert("❌ Select Class");
  return false;
}

if (!quota) {
  alert("❌ Select Quota");
  return false;
}

// 🔥 SAVE QUOTA
chrome.storage.local.set({
  quota: quota
});

  // 🚆 TRAIN
  let train = document.getElementById("train-no").value.trim();

  if (!/^\d{5}/.test(train)) {
    alert("❌ Enter valid Train Number");
    return false;
  }

  // 📱 MOBILE
  let mobile = document.getElementById("mobile").value.trim();

  if (!/^\d{10}$/.test(mobile)) {
    alert("❌ Enter valid Mobile Number");
    return false;
  }

  // 👤 PASSENGER 1 (mandatory)
  let name1 = document.getElementById("p1-name").value.trim();
  let age1 = document.getElementById("p1-age").value.trim();
  let gender1 = document.getElementById("p1-gender").value;

  if (!name1) {
    alert("❌ Passenger 1 Name required");
    return false;
  }

  if (!/^\d+$/.test(age1)) {
    alert("❌ Passenger 1 Age invalid");
    return false;
  }

  if (!gender1) {
    alert("❌ Passenger 1 Gender required");
    return false;
  }

  // 👥 OPTIONAL PASSENGERS (2–4)
  for (let i = 2; i <= 4; i++) {

    let name = document.getElementById(`p${i}-name`).value.trim();
    let age = document.getElementById(`p${i}-age`).value.trim();
    let gender = document.getElementById(`p${i}-gender`).value;

    if (name || age || gender) {

      if (!name) {
        alert(`❌ Passenger ${i} Name required`);
        return false;
      }

      if (!/^\d+$/.test(age)) {
        alert(`❌ Passenger ${i} Age invalid`);
        return false;
      }

      if (!gender) {
        alert(`❌ Passenger ${i} Gender required`);
        return false;
      }
    }
  }

  // 💳 PAYMENT
  let payment = document.getElementById("payment-mode").value;

  if (!payment) {
    alert("❌ Select Payment Mode");
    return false;
  }

  return true;
}

  
  // ==============================
  // 🔥 SAVE BUTTON (FINAL FIX)
  // ==============================
  document.getElementById("submit-btn").onclick = () => {

    if (!validateForm()) return;

    finalData.irctc_credentials = {
      user_name: document.getElementById("irctc-login").value,
      password: document.getElementById("irctc-password").value
    };
// 🔥 TRAIN FIX ADD
let trainInput = document.getElementById("train-no").value;
let trainNo = trainInput.split("-")[0].trim();

finalData.journey_details = {
  ...finalData.journey_details,
  from: document.getElementById("from").value,
  to: document.getElementById("to").value,
  class: document.getElementById("journey-class-input").value,
  quota: document.getElementById("quota-input").value,
  train_no: trainNo, // 🔥 FIXED
  mobile: document.getElementById("mobile").value,
  payment_mode: document.getElementById("payment-mode").value,
  passengers: []
};

    // ======================
    // 🔥 PASSENGER SAVE FIX
    // ======================
    for (let i = 1; i <= 4; i++) {

      let name = document.getElementById(`p${i}-name`).value.trim();
      let age = document.getElementById(`p${i}-age`).value.trim();
      let gender = document.getElementById(`p${i}-gender`).value;
      let berth = document.getElementById(`p${i}-berth`).value;

      if (name && age && gender) {
        finalData.journey_details.passengers.push({
          name,
          age,
          gender,
          berth
        });
      }
    }

    console.log("🚀 FINAL DATA:", finalData);

    chrome.storage.local.set(finalData, () => {
      alert("✅ Data Saved Successfully");
    });
  };



  // ==============================
  // 🔄 LOAD DATA
  // ==============================
  chrome.storage.local.get(null, (data) => {

    let d = data.journey_details || {};

    if (d.payment_mode) {
      document.getElementById("payment-mode").value = d.payment_mode;
    }

  });




 function initButtons() {

  // 🔥 AUTO LOAD EMAIL
  chrome.storage.local.get(["user_email"], (res) => {
    if (res.user_email) {
      let emailInput = document.getElementById("user-email");
      if (emailInput) {
        emailInput.value = res.user_email;
      }
    }
  });

  // 👉 SAVE EMAIL
  const saveBtn = document.getElementById("save-email-btn");

  if (saveBtn) {
    saveBtn.addEventListener("click", () => {

      let email = document.getElementById("user-email").value.trim().toLowerCase();

      if (!email) {
        alert("Enter email");
        return;
      }

      chrome.storage.local.set({ user_email: email }, () => {
        alert("Saved ✅");
      });

    });
  }

  // 👉 START BOOKING (SECURE VERSION 🔐)
  const startBtn = document.getElementById("connect-btn");

  if (startBtn) {
    startBtn.addEventListener("click", async () => {

      let emailInput = document.getElementById("user-email");

      if (!emailInput) {
        alert("Email input not found");
        return;
      }

      let email = emailInput.value.trim().toLowerCase();

      if (!email) {
        alert("Enter email first");
        return;
      }

      // 🔥 BUTTON LOADING STATE
      startBtn.disabled = true;
      startBtn.innerText = "Checking...";

      try {

        let response = await fetch(
          "https://estrogen-stoplight-afford.ngrok-free.dev/tatkal_safer/api/check-plan.php?email=" 
          + encodeURIComponent(email)
        );

        let data = await response.json();

        console.log("STATUS:", data.status);

        if (data.status === "active") {

          // 🔐 DOUBLE VERIFY (ANTI BYPASS)
          let verifyAgain = await fetch(
            "https://estrogen-stoplight-afford.ngrok-free.dev/tatkal_safer/api/check-plan.php?email=" 
            + encodeURIComponent(email)
          );

          let verifyData = await verifyAgain.json();

          if (verifyData.status !== "active") {
            alert("Plan expired ❌");
            startBtn.disabled = false;
            startBtn.innerText = "Start Booking";
            return;
          }

          alert("Your Plan Activated ✅");

          chrome.runtime.sendMessage({ action: "START_BOOKING" });

        } else {

          alert("Use after buying our plan ❌");

          window.open(
            "https://estrogen-stoplight-afford.ngrok-free.dev/tatkal_safer/plans.php",
            "_blank"
          );

        }

      } catch (e) {
        alert("Server error");
        console.log("ERROR:", e);
      }

      // 🔄 RESET BUTTON
      startBtn.disabled = false;
      startBtn.innerText = "Start Booking";

    });
  }

}


// ==============================
// RUN AFTER PAGE LOAD
// ==============================
if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", initButtons);
} else {
  initButtons();
}

});


document.addEventListener("DOMContentLoaded", () => {

  const emailInput = document.getElementById("user-email");
  const statusText = document.getElementById("email-status");

  if (!emailInput || !statusText) return;

  let timeout = null;

  emailInput.addEventListener("input", () => {

    clearTimeout(timeout);

    let email = emailInput.value.trim().toLowerCase();

    // 🔥 email format check
    let valid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

    if (!email) {
      statusText.textContent = "";
      return;
    }

    // ❌ SAME PLACE ERROR
    if (!valid) {
      statusText.textContent = "Invalid Email";
      statusText.style.color = "red";
      return;
    }

    // 🔄 debounce
    timeout = setTimeout(async () => {

      statusText.textContent = "Checking...";
      statusText.style.color = "#ccc";

      try {

        let res = await fetch(
          "https://estrogen-stoplight-afford.ngrok-free.dev/tatkal_safer/api/check-plan.php?email=" 
          + encodeURIComponent(email)
        );

        let data = await res.json();

        if (data.status === "active") {
          statusText.textContent = "Email Verified";
          statusText.style.color = "#00ffcc";
        } else {
          statusText.textContent = "Email Not Found";
          statusText.style.color = "#59cbe8";
        }

      } catch (e) {
        statusText.textContent = "Error ⚠️";
        statusText.style.color = "orange";
      }

    }, 600);

  });

});


// ==============================
// 🔥 AUTOCOMPLETE (PRO VERSION)
// ==============================
function setupAuto(inputId) {

  const input = document.getElementById(inputId);

  let list = document.createElement("div");
  list.style.background = "white";
  list.style.color = "black";
  list.style.maxHeight = "150px";
  list.style.overflowY = "auto";
  list.style.position = "absolute";
  list.style.border = "1px solid #ccc";
  list.style.zIndex = "9999";

  document.body.appendChild(list);

  let selectedIndex = -1;
  let currentItems = [];

  input.addEventListener("input", () => {

    let val = input.value.toUpperCase();
    list.innerHTML = "";
    selectedIndex = -1;
    currentItems = [];

    if (!val || !stations || !stations.length) return;

    const rect = input.getBoundingClientRect();
    list.style.left = rect.left + "px";
    list.style.top = (rect.bottom + window.scrollY) + "px";
    list.style.width = rect.width + "px";

    let result = stations.filter(s =>
      s.code.includes(val) || s.name.includes(val)
    ).slice(0, 5);

    currentItems = result;

    result.forEach((s, index) => {
      let item = document.createElement("div");
      item.innerText = `${s.name} - ${s.code}`;
      item.style.padding = "6px";
      item.style.cursor = "pointer";

      // 🔥 hover effect
      item.onmouseover = () => highlight(index);
      item.onclick = () => selectItem(index);

      list.appendChild(item);
    });

    // 🔥 AUTO SELECT FIRST
    if (result.length > 0) {
      highlight(0);
    }

  });

  // ==============================
  // 🔥 KEYBOARD CONTROL
  // ==============================
  input.addEventListener("keydown", (e) => {

    if (!currentItems.length) return;

    if (e.key === "ArrowDown") {
      e.preventDefault();
      selectedIndex = (selectedIndex + 1) % currentItems.length;
      highlight(selectedIndex);
    }

    if (e.key === "ArrowUp") {
      e.preventDefault();
      selectedIndex = (selectedIndex - 1 + currentItems.length) % currentItems.length;
      highlight(selectedIndex);
    }

    if (e.key === "Enter") {
      e.preventDefault();
      if (selectedIndex >= 0) {
        selectItem(selectedIndex);
      }
    }

  });

  // ==============================
  // 🔥 FUNCTIONS
  // ==============================
  function highlight(index) {
    let items = list.children;

    for (let i = 0; i < items.length; i++) {
      items[i].style.background = i === index ? "#e0e0e0" : "white";
    }

    selectedIndex = index;
  }

  function selectItem(index) {
    let s = currentItems[index];
    input.value = `${s.name} - ${s.code}`;
    list.innerHTML = "";
  }

  // 🔥 click outside hide
  document.addEventListener("click", (e) => {
    if (!input.contains(e.target)) {
      list.innerHTML = "";
    }
  });

}

// INIT
document.addEventListener("DOMContentLoaded", () => {
  setupAuto("from");
  setupAuto("to");
});





// ==============================
// 🚆 TRAIN AUTOCOMPLETE (FINAL PRO VERSION)
// ==============================
document.addEventListener("DOMContentLoaded", () => {

  const input = document.getElementById("train-no");
  const list = document.getElementById("train-suggestions");

  if (!input || !list) return;

  let currentIndex = -1;
  let items = [];

  input.addEventListener("input", () => {

    let val = input.value.toLowerCase().trim();
    list.innerHTML = "";
    currentIndex = -1;

    if (!val || typeof trainNumbers === "undefined") return;

    // 🔥 SMART FILTER (MULTIPLE RESULT)
    let result = trainNumbers.filter(t => {
      let txt = t.toLowerCase();
      return txt.startsWith(val) || txt.includes(" " + val) || txt.includes(val);
    }).slice(0, 10);

    result.forEach((t, index) => {

      let item = document.createElement("div");
      item.innerText = t;
      item.style.padding = "6px";
      item.style.cursor = "pointer";

      item.onclick = () => {
        input.value = t; // 🔥 FULL TEXT (number + name)
        list.innerHTML = "";
      };

      list.appendChild(item);
    });

    items = list.querySelectorAll("div");
  });

  // ======================
  // ⌨️ KEYBOARD SUPPORT
  // ======================
  input.addEventListener("keydown", (e) => {

    if (!items.length) return;

    if (e.key === "ArrowDown") {
      currentIndex++;
      highlight();
    }

    else if (e.key === "ArrowUp") {
      currentIndex--;
      highlight();
    }

    else if (e.key === "Enter") {
      e.preventDefault();
      if (currentIndex > -1 && items[currentIndex]) {
        items[currentIndex].click();
      }
    }
  });

  function highlight() {
    items.forEach(item => {
      item.style.background = "white";
      item.style.color = "black";
    });

    if (currentIndex >= items.length) currentIndex = 0;
    if (currentIndex < 0) currentIndex = items.length - 1;

    items[currentIndex].style.background = "#3b82f6";
    items[currentIndex].style.color = "#fff";
  }

});



// ==============================
// 🔥 OPEN DASHBOARD BUTTON
// ==============================
document.addEventListener("DOMContentLoaded", () => {

  const openBtn = document.getElementById("openBtn");

  if (openBtn) {
    openBtn.addEventListener("click", () => {

      chrome.tabs.create({
        url: chrome.runtime.getURL("dashboard.html")
      });

    });
  }

});



